package com.leyou.auth.task;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.mapper.ApplicationInfoMaapper;
import com.leyou.common.auth.JwtUtils;
import com.leyou.common.auth.entity.AppInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author xiuer
 * @description 授权微服务获取token
 * @create 2019/7/11 10:31
 */
@Component
@Slf4j
public class PrivileageAuthTokenHolder {

    @Autowired
    private JwtProperties properties;
    @Autowired
    private ApplicationInfoMaapper appMaapper;

    private String token;

    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L;

    /**
     * 24h执行一次 生成token
     */
    @Scheduled(fixedDelay = TOKEN_REFRESH_INTERVAL)
    private void loadingAuthToken() {
        try {
            //准备载荷, 查询权限服务列表
            List<Long> longs = appMaapper.queryPrivilegeList(properties.getApp().getId());
            AppInfo appInfo = new AppInfo();
            appInfo.setServiceName(properties.getApp().getSecret());
            appInfo.setTargetList(longs);
            //生成token
            token = JwtUtils.generateTokenExpireInMinutes(appInfo, properties.getPrivateKey(),
                    properties.getApp().getAppExpire());
            log.info("【授权微服务】定时获取token成功：token为{}", token);
        } catch (Exception e) {
            log.error("【授权微服务】生成token失败：原因{}", e.getMessage(), e);
        }
    }

    public String getToken() {
        return token;
    }
}
